package com.tianye.salon.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.druid.util.StringUtils;
import com.tianye.salon.constants.ServiceCodeConstants;
import com.tianye.salon.service.BaseService;
import com.tianye.salon.util.AverageImageScale;
import com.tianye.salon.util.ProfileUtil;
import com.tianye.salon.util.UploadUtils;

public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(BaseController.class);

	public Map<String, Object> getPageResult(BaseService ibs, Map<String, Object> map) throws Exception {
		return ibs.queryPageResult(map);
	}

	protected Map<String, Object> getFailRtn(String msg) {
		Map<String, Object> rtn = new HashMap<String, Object>();
		rtn.put("code", ServiceCodeConstants.FAIL_RTN);
		rtn.put("msg", msg);
		rtn.put("data", null);
		return rtn;
	}

	/**
	 * 获取成功返回
	 * 
	 * @param data
	 * @return
	 * @author tianyunyun
	 * @date 2016年11月4日下午12:15:48
	 */
	protected Map<String, Object> getSuccessRtn(Object data) {
		Map<String, Object> rtn = new HashMap<String, Object>();
		rtn.put("code", ServiceCodeConstants.SUCCESS_RTN);
		rtn.put("msg", "");
		rtn.put("data", data);
		return rtn;
	}

	/**
	 * 获取成功返回
	 * 
	 * @param data
	 * @return
	 * @author tianyunyun
	 * @date 2016年11月4日下午12:15:48
	 */
	protected Map<String, Object> getSuccessRtn(Object data, String msg) {
		Map<String, Object> rtn = new HashMap<String, Object>();
		rtn.put("code", ServiceCodeConstants.SUCCESS_RTN);
		rtn.put("msg", msg);
		rtn.put("data", data);
		return rtn;
	}

	/**
	 * 获取成功返回
	 * 
	 * @param data
	 * @return
	 * @author tianyunyun
	 * @date 2016年11月4日下午12:15:48
	 */
	protected Map<String, Object> getRtnCode(String msg, Integer code) {
		Map<String, Object> rtn = new HashMap<String, Object>();
		rtn.put("code", code);
		rtn.put("msg", msg);
		rtn.put("data", "");
		return rtn;
	}

	// 上传图片（包含多张图片）统一处理方法
	public List<Map<String, String>> uploadFile(HttpServletRequest request, String images_upload_path)
			throws Exception {
		MultipartHttpServletRequest multipartRequest = null;
		List<Map<String, String>> fileNames = new ArrayList<>();
		if (request instanceof MultipartHttpServletRequest) {
			multipartRequest = (MultipartHttpServletRequest) request;
		}
		if (StringUtils.isEmpty(images_upload_path)) {
			images_upload_path = ProfileUtil.getInstance().read("prop.properties", "images_upload_path");
		}
		if (null != multipartRequest) {
			MultiValueMap<String, MultipartFile> values = multipartRequest.getMultiFileMap();
			Set<String> keys = values.keySet();// 遍历文件
			for (String key : keys) {
				List<MultipartFile> mutiFiles = values.get(key);
				for (MultipartFile imgFile : mutiFiles) {
					if (null != imgFile && !imgFile.isEmpty()) {
						// 保存原图
						Map<String, Object> fileNameMap = saveNormalFile(imgFile,
								request.getSession().getServletContext(), images_upload_path);
						// 缩略图
						String filename = resizeimage((File) fileNameMap.get("file"),
								request.getSession().getServletContext(), images_upload_path, null, null);
						Map<String, String> map = new HashMap<>();
						map.put("filename", (String) fileNameMap.get("filename"));
						map.put("small", filename);
						if (!fileNames.contains(map)) {
							fileNames.add(map);
						}
					}
				}
			}
			// 有存在一个filename多个file的情况
			/*
			 * Iterator<String> it = multipartRequest.getFileNames(); //
			 * 返回上传文件列表，map中存大图跟小图路径 while (it.hasNext()) { String fileName =
			 * it.next(); if (null != fileName && !"".equals(fileName)) { //
			 * 存储图片路径 // 获得第1张图片（根据前台的name名称得到上传的文件） MultipartFile imgFile =
			 * multipartRequest.getFile(fileName); if (null != imgFile &&
			 * !imgFile.isEmpty()) { //保存原图 Map<String, Object> fileNameMap =
			 * saveNormalFile(imgFile, request.getSession().getServletContext(),
			 * images_upload_path); //缩略图 String filename =
			 * resizeimage((File)fileNameMap.get("file"),
			 * request.getSession().getServletContext(), images_upload_path,
			 * null, null); Map<String, String> map = new HashMap<>();
			 * map.put("filename", (String) fileNameMap.get("filename"));
			 * map.put("small", filename); if (!fileNames.contains(map)) {
			 * fileNames.add(map); } } } }
			 */
		}
		return fileNames;
	}
	
	/**
	 * 上传原始文件
	 * 
	 * @param file
	 * @param ctx
	 * @param file_upload_path
	 * @return
	 * @throws BusinessException
	 */
	public Map saveNormalFile(MultipartFile file, ServletContext ctx, String file_upload_path)
			throws Exception {
		Map map = new HashMap();
		// 得到文件原始名称
		String origName = file.getOriginalFilename();
		// 得到文件后缀名
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		// 获取文件上传路径
		String file_path_Prefix = ProfileUtil.getInstance().read("prop.properties", "file_path_Prefix");
		try {
			// 原文件名
			map.put("orginFilename", origName);
			//区分项目图片logo
			String filename = UploadUtils.generateFilename(file_upload_path, ext);
			// 保存文件名，用于存储
			map.put("filename", filename);
			String realpath = "";
			// 如果配有Prefix目录，以此为准，否则保存到tomcat webapp 项目根目录下
			if (file_path_Prefix != null && file_path_Prefix.length() > 0) {
				realpath = file_path_Prefix + filename;
			} else {
				realpath = ctx.getRealPath(filename);
				if (realpath == null) {
					realpath = ctx.getRealPath("/") + filename;
				}
			}
			File destFile = new File(realpath);
			destFile = UploadUtils.getUniqueFile(destFile);
			store(file, destFile);
			map.put("file", destFile);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 上传文件公共方法
	 * 
	 * @param file
	 * @param dest
	 * @throws IOException
	 */
	public void store(MultipartFile file, File dest) throws IOException {
		try {
			UploadUtils.checkDirAndCreate(dest.getParentFile());
			file.transferTo(dest);
		} catch (IOException e) {
			logger.error("Transfer file error when upload file", e);
			throw e;
		}
	}
	/**
	 * 指定大小缩放图片
	 * 
	 * @param file
	 * @param ctx
	 * @param images_upload_path
	 * @param width
	 * @param height
	 * @return
	 * @throws BusinessException
	 */
	public String resizeimage(File file, ServletContext ctx, String images_upload_path, String width, String height)
			throws Exception {
		String name = file.getName();
		String ext = FilenameUtils.getExtension(name).toLowerCase(Locale.ENGLISH);
		String origName = name.substring(0, name.lastIndexOf("."));
		if (width == null) {
			// 默认缩放图片的宽度
			width = ProfileUtil.getInstance().read("prop.properties", "images_resize_width");
		}
		if (height == null) {
			// 默认缩放图片的高度
			height = ProfileUtil.getInstance().read("prop.properties", "images_resize_height");
		}
		// 图片存放根路径
		String file_path_Prefix = ProfileUtil.getInstance().read("prop.properties", "file_path_Prefix");
		try {
			String flname = origName + "_" + width + "_" + height;
			//String flname = origName + "small";
			flname = UploadUtils.generateByFilename(images_upload_path, flname, ext);
			String realpath = "";
			// 如果配有Prefix目录，以此为准，否则保存到tomcat webapp 项目根目录下
			if (file_path_Prefix != null && file_path_Prefix.length() > 0) {
				realpath = file_path_Prefix + flname;
			} else {
				realpath = ctx.getRealPath(flname);
				if (realpath == null) {
					realpath = ctx.getRealPath("/") + flname;
				}
			}
			File fileless = new File(realpath);
			// 按指定大小缩放图片
			AverageImageScale.resizeFix(file, fileless, Integer.parseInt(width), Integer.parseInt(height));
			return flname;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
